import {
    OrderDetail
} from './order-detail.model'
import {
    Order
} from './../order/order.model'
import {
    Member
} from './../member/member.model'
import {
    ApplySub
} from './../apply-sub/apply-sub.model'
import Toast from '@vant/weapp/toast/toast'
const orderDetail = new OrderDetail()
const order = new Order()
const member = new Member()
const applySub = new ApplySub()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        order: '',
        currentId: '',
        currentPrice: '',
        refundModel: false,
        cancelModel: false,
        currentLsh: '',
        isRefresh: false,
        refreshZtText: `刷新状态`,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this._loadData(options.id)
    },

    /**
     * 获取所有数据
     * @param {*} id
     */
    _loadData(id) {
        let that = this
        that.getOrderData(id)
    },

    /**
     * 获取订单详情
     * @param {*} id
     */
    getOrderData(id) {
        let that = this
        orderDetail.getOrderData(id).then((res) => {
            let data = res.data
            if (data.sbyy == '' || data.sbyy == null) {
                data.sbyy = '无'
            }
            that.setData({
                order: data
            })
        })
    },

    /**
     * 支付
     * @param {*} options
     */
    doPay(options) {
        let order_id = orderDetail.getDataSet(options, 'order_id'),
            order_sn = orderDetail.getDataSet(options, 'order_sn'),
            total_amount = orderDetail.getDataSet(options, 'total_amount'),
            subscribe_id = orderDetail.getDataSet(options, 'subscribe_id'),
            orderData = {
                order_id: order_id,
                order_sn: order_sn,
                total_amount: total_amount,
                subscribe_id: subscribe_id
            }
        orderDetail.placeOrder(orderData).then((res) => {
            orderDetail.pay(res).then(() => {
                member.getMemberData().then((result) => {
                    let userInfo = orderDetail.getStorage('userInfo')
                    userInfo.member = result.data.member
                    orderDetail.setStorage('userInfo', userInfo)
                }).then(() => {
                    Toast({
                        type: 'success',
                        message: '支付成功',
                        onClose: () => {
                            wx.reLaunch({
                                url: '/pages/order/order?status=2&page=1'
                            })
                        },
                    })
                })
            }).catch(() => {
                Toast.fail('支付失败')
            })
        })
    },

    /**
     * 取消订单
     * @param {*} options
     */
    onConfirmCancel(options) {
        let that = this,
            id = orderDetail.getDataSet(options, 'id'),
            lsh = orderDetail.getDataSet(options, 'lsh')
        // 取消交管中心订单
        if (lsh) {
            orderDetail.cancelCarOrder(lsh).then((res) => {
                let data = res.data
                if (1 == data.code || (0 == data.code && '已取消' == data.msg)) {
                    that.cancelSuccess(id)
                } else {
                    that.setData({
                        cancelModel: false
                    })
                    Toast({
                        message: '已到检车日期或日期已过，取消预约失败',
                        mask: true,
                        duration: 3000
                    })
                }
            })
            // 取消本地订单
        } else {
            orderDetail.cancelOrder(id).then(() => {
                that.setData({
                    cancelModel: false
                })
            }).then(() => {
                Toast({
                    type: 'success',
                    message: '取消成功',
                    onClose: () => {
                        wx.reLaunch({
                            url: '/pages/order/order?status=4&page=1&searchedTitle='
                        })
                    },
                })
            })
        }
    },

    /**
     * 取消订单成功
     * @param {*} id
     */
    cancelSuccess(id) {
        let that = this
        orderDetail.cancelOrder(id).then(() => {
            that.setData({
                cancelModel: false
            })
            // 更新订单状态
            order.updateOrderZt({
                order_id: id,
                zt: -1
            }).then(() => {
                // orderDetail.sendSubscribeMessage(id, 'subscribeCanceled')
                wx.hideLoading()
                Toast({
                    type: 'success',
                    message: '预约已取消',
                    onClose: () => {
                        wx.reLaunch({
                            url: '/pages/order/order?status=4&page=1&searchedTitle='
                        })
                    },
                })
            })
        })
    },

    /**
     * 刷新状态
     * @param {*} options
     */
    // onRefreshZt(options) {
    //     wx.showLoading({
    //         title: '查询中...',
    //         mask: true
    //     })
    //     let that = this,
    //         order_id = order.getDataSet(options, 'order_id'),
    //         lsh = order.getDataSet(options, 'lsh')
    //     // 查询预约信息
    //     applySub.checkSubscribeStatus(lsh).then((res) => {
    //         if (1 == res.data.code) {
    //             let data = JSON.parse(res.data.data),
    //                 zt = data.zt,
    //                 sbyy = data.hasOwnProperty('sbyy') ? data.sbyy : ''
    //             // 更新订单状态
    //             order.updateOrderZt({
    //                 order_id: order_id,
    //                 zt: zt,
    //                 sbyy: sbyy
    //             }).then(() => {
    //                 switch (zt) {
    //                     case 2: // 预约成功
    //                         // 传递订单给收银系统
    //                         applySub.sendOrderDataToPayment(order_id)
    //                         order.sendSubscribeMessage(order_id, 'subscribeComplete')
    //                         break;
    //                     case -1: // 取消
    //                         order.restoreSubscribeNumber(order_id)
    //                         order.cancelOrder(order_id)
    //                         break;
    //                     case -2: // 审核不通过
    //                         order.restoreSubscribeNumber(order_id)
    //                         order.cancelOrder(order_id)
    //                         order.sendSubscribeMessage(order_id, 'failed')
    //                         break;
    //                 }
    //                 that.refreshZtSuccess(order_id)
    //             })
    //         } else {
    //             wx.hideLoading({
    //                 success: () => {
    //                     Toast('刷新失败，请稍后重试')
    //                 },
    //             })
    //         }
    //     })
    //     that.setData({
    //         isRefresh: true,
    //         refreshZtText: `60`,
    //     })
    //     let second = 60
    //     const timer = setInterval(() => {
    //         second--
    //         if (second) {
    //             that.setData({
    //                 refreshZtText: `${second}`,
    //             })
    //         } else {
    //             clearInterval(timer)
    //             that.setData({
    //                 isRefresh: false,
    //                 refreshZtText: `刷新状态`,
    //             })
    //         }
    //     }, 1000)
    // },

    /**
     * 刷新状态成功
     * @param {*} order_id 订单ID
     */
    // refreshZtSuccess(order_id) {
    //     let that = this
    //     wx.hideLoading()
    //     Toast({
    //         type: 'success',
    //         message: '刷新成功',
    //         onClose: () => {
    //             that._loadData(order_id)
    //         },
    //     })
    // },

    /**
     * 退款
     */
    onConfirmRefund() {
        let that = this
        orderDetail.refundOrder(that.data.currentId).then(() => {
            that.setData({
                refundModel: false
            })
        }).then(() => {
            wx.navigateTo({
                url: `/pages/refund/refund?price=${that.data.currentPrice}`,
            })
        })
    },

    /**
     * 打开取消订单窗口
     * @param {*} options
     */
    onOpenCancelModel(options) {
        let that = this,
            id = orderDetail.getDataSet(options, 'id')
        that.setData({
            currentId: id,
            cancelModel: true,
        });
    },

    /**
     * 打开取消订单窗口
     * @param {*} options
     */
    onOpenCancelModel2(options) {
        let that = this,
            id = orderDetail.getDataSet(options, 'id'),
            lsh = orderDetail.getDataSet(options, 'lsh')
        that.setData({
            currentId: id,
            currentLsh: lsh,
            cancelModel: true,
        });
    },

    /**
     * 打开退款窗口
     * @param {*} options
     */
    onOpenRefundModel(options) {
        let that = this,
            id = orderDetail.getDataSet(options, 'id'),
            price = orderDetail.getDataSet(options, 'price')
        that.setData({
            currentId: id,
            currentPrice: price,
            refundModel: true,
        });
    },

    /**
     * 关闭申请窗口
     */
    onCloseModel() {
        let that = this
        that.setData({
            cancelModel: false,
            refundModel: false
        });
    },

    /**
     * 跳转到评论列表
     * @param {*} options
     */
    onJumpCommentList() {
        wx.navigateTo({
            url: `/pages/comment/comment`,
        })
    },

    /**
     * 跳转到评论
     * @param {*} options
     */
    onJumpCommentWrite(options) {
        let id = orderDetail.getDataSet(options, 'id')
        wx.navigateTo({
            url: `/pages/comment-write/comment-write?id=${id}`,
        })
    },

    /**
     * 重新下单
     */
    onReorder() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
})